package com.yc.thread.pc;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 实现A 执行完 执行B 再执行C
 */
public class ProductConsumerNew2 {
    public static void main(String[] args){
        System.out.println(Runtime.getRuntime().availableProcessors());
//        SourceNew2 s = new SourceNew2();
//        // 线程A 生产
//        new Thread(() -> {
//            for(int i=0; i<=10; i++) {
//                s.printA();
//            }
//        }, "A").start();
//
//        new Thread(() -> {
//            for(int i=0; i<=10; i++) {
//                s.printB();
//            }
//        }, "B").start();
//
//        new Thread(() -> {
//            for(int i=0; i<=10; i++) {
//                s.printC();
//            }
//        }, "C").start();

    }
}

// 定义资源
class SourceNew2{
    // 拿到一个锁
    Lock lock = new ReentrantLock();
    Condition condition1 = lock.newCondition();
    Condition condition2 = lock.newCondition();
    Condition condition3 = lock.newCondition();

    private int number = 1; // 1-->A  2-->B  3-->C
    public void printA() {
        lock.lock();
        try {
            if (number != 1) {
                condition1.await();
            }
            System.out.println(Thread.currentThread().getName() + "A 执行了");
            number = 2;
            condition2.signal();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void printB() {
        lock.lock();
        try {
            if (number != 2) {
                condition2.await();
            }
            System.out.println(Thread.currentThread().getName() + "B 执行了");
            number = 3;
            condition3.signal();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void printC() {
        lock.lock();
        try {
            if (number != 3) {
                condition3.await();
            }
            System.out.println(Thread.currentThread().getName() + "c 执行了");
            number = 1;
            condition1.signal();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }

    }
}
